package top.codingfly.filter.wrapper;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

public class HttpDataRequestWrapper extends HttpServletRequestWrapper {
    private static final Charset CHARSET = StandardCharsets.UTF_8;
    private String body;

    public HttpDataRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body = getBodyStringFromRequest(request);
    }

    /**
     * 获取请求Body
     * @param request
     * @return
     */
    private String getBodyStringFromRequest(final ServletRequest request) throws IOException {
        String contentType = StringUtils.isNotBlank(request.getContentType())? request.getContentType().toLowerCase():"";

        // multipart/form-data 和 x-www-form-urlencoded 请求，不能直接读取 request.getInputStream() ，
        // 会导致后续的Controller获取不到 multipart/form-data ， x-www-form-urlencoded 参数，
        // 即使当前类的getInputStream()方法把流数据塞回到RequestWrapper
        // 因此 multipart/form-data 和 x-www-form-urlencoded 用 request.getParameter() 获取
        if (contentType.contains("multipart/form-data") || contentType.contains("x-www-form-urlencoded")) {
            StringBuffer sb = new StringBuffer();
            Enumeration<String> pars = request.getParameterNames();
            boolean hasBodyParam = false;
            while (pars.hasMoreElements()) {
                String n = pars.nextElement();
                sb.append(n + "=" + request.getParameter(n) + "&");
                hasBodyParam = true;
            }
            String bodyString = sb.toString();
            bodyString = hasBodyParam ? bodyString.substring(0, bodyString.length() - 1) : bodyString;
            return bodyString;
        }

        return new String(StreamUtils.copyToByteArray(request.getInputStream()), CHARSET);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes(CHARSET));
        return new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    public String getBodyString() {
        return body;
    }

}
